package com.yenroc.ho.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author： heyanpeng
 * @date： 2021/7/27
 */
public class NettyServer {
    private final Logger log = LoggerFactory.getLogger(NettyServer.class);

    private static class SingletionNettyServer {
        static  final NettyServer instance=new NettyServer();
    }

    public static NettyServer getInstance(){
        return  SingletionNettyServer.instance;
    }
    private EventLoopGroup master;

    private EventLoopGroup slaver;

    private ServerBootstrap serverBootstrap;

    private ChannelFuture channelFuture;

    public void start() throws InterruptedException {

        //NioEventLoopGroup是用来处理IO操作的多线程事件循环器
        EventLoopGroup bossGroup  = new NioEventLoopGroup();  // 用来接收进来的连接
        EventLoopGroup workerGroup  = new NioEventLoopGroup();// 用来处理已经被接收的连接
        try{
            ServerBootstrap server =new ServerBootstrap();//是一个启动NIO服务的辅助启动类
            server.group(bossGroup,workerGroup )
                    .channel(NioServerSocketChannel.class)  // 这里告诉Channel如何接收新的连接
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new NettyServerInitializer());
//            server.option(ChannelOption.SO_BACKLOG,128);
//            server.childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = server.bind(9999).sync();// 绑定端口，开始接收进来的连接
            log.info("netty 启动完毕=============");
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
